package com.ikingtech.platform.service.cluster.server;

import com.ikingtech.framework.sdk.cluster.client.ClusterClient;
import com.ikingtech.framework.sdk.cluster.node.ClusterNode;
import com.ikingtech.framework.sdk.cluster.node.ClusterNodeManager;
import com.ikingtech.framework.sdk.cluster.propertities.ClusterProperties;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.cluster.entity.ClusterNodeDO;
import com.ikingtech.platform.service.cluster.service.ClusterNodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.List;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class ClusterInitializer implements ApplicationRunner {

    private final ClusterNodeManager nodeManager;

    private final ClusterNodeService nodeService;

    private final ClusterProperties properties;

    private final ClusterServer server;

    private final ClusterClient client;

    @Override
    public void run(ApplicationArguments args) {
        if (!this.properties.isEnable()) {
            return;
        }
        List<ClusterNodeDO> nodeEntities = this.nodeService.list();
        nodeEntities.addAll(Tools.Coll.convertList(this.properties.getNode(), node -> {
            List<String> nodeInfo = Tools.Str.split(node, ":");
            ClusterNodeDO nodeEntity = new ClusterNodeDO();
            nodeEntity.setAddress(nodeInfo.get(0));
            nodeEntity.setPort(Integer.valueOf(nodeInfo.get(1)));
            return nodeEntity;
        }));
        if (Tools.Coll.isNotBlank(nodeEntities)) {
            this.nodeManager.putAll(Tools.Coll.convertMap(nodeEntities, node -> Tools.Str.join(node.getAddress(), node.getPort().toString(), ":"), node -> Tools.Bean.copy(node, ClusterNode.class)));
        }
        // 启动netty服务
        new Thread(this.server::run).start();
        // 初始化netty客户端
        this.client.init();
        // 启动心跳线程
        new ClusterNodeHeartBeatThread(this.client).start();
    }
}
